<template>
  <table class="customize-table">
    <thead>
    <th class="customize-table-checkbox-th" v-if="options.showCheckBox || true">
      <input :checked="allChecked" @change="handleAllCheckboxChange($event)" type="checkbox"/>
    </th>
    <th v-for="column in columns" :key="column.field">{{ column.desc }}</th>
    </thead>
    <tbody>
    <tr v-for="(item,index) in data" :key="index" :id="index">
      <td class="customize-table-checkbox-th" v-if="options.showCheckBox || true">
        <input :checked="refData[index].isChecked" @change="handleRowCheckBoxChange(index,$event)" type="checkbox"/>
      </td>
      <td v-for="column in columns">{{ item[column.field] }}</td>
    </tr>
    </tbody>
  </table>
</template>
<script setup>
import {ref, toRaw, toRef, computed} from 'vue';
//回调调用父组件方法
const emits = defineEmits(["loadSuccess"]);
const props = defineProps({
  columns: [],
  data: [],
  options:{},
});

const optionsDefault = {};

const {data, columns, options} = props;

let refOptions  = ref(options);
let refData = toRef(data);
let allChecked = ref(false);

emits("loadSuccess", toRaw(data));

const handleAllCheckboxChange = ((event) => {
  console.log(event.target.checked);
  refData.value.forEach((item) => {
    item.isChecked = true;
  })
  allChecked.value = true;
});

const handleRowCheckBoxChange = ((index, event) => {
  refData.value[index].isChecked = event.target.checked;
  if (!event.target.checked) {
    allChecked.value = false;
  }else {
    allChecked.value = true;
    refData.value.forEach((item) =>{
      if(!item.isChecked){
        allChecked.value = false;
      }
    });
  }
});

const getCheckedRows = ()=>{
  const dValue = toRaw(data);
  let temp = [];
  refData.value.forEach((item,index) =>{
    if(item.isChecked){
      temp.push(toRaw(refData.value[index]));
    }
  });
  return temp;
}

defineExpose({getCheckedRows });

</script>
<style scoped>


.customize-table {
  width: 100%;
  border: 1px solid #EBEEF5;
  border-collapse: collapse;
}

.customize-table td, th {
  border: 1px solid #EBEEF5;
  height: 35px;
}

.customize-table th {
  color: #94979D;
  font-size: 16px;
}

.customize-table td {
  color: #66686B;
  padding-left: 10px;
  font-size: 14px;
}

.customize-table-checkbox-th {
  width: 50px;
  padding-left: 0px !important;
  text-align: center;
}

</style>